<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use App\Services\BaseConfigService;
use App\Services\BaseUserService;
use App\Services\BaseBannerService;
use App\Services\BaseUserAddressService;
use App\Services\ArticleCateService;
use App\Services\ArticleNewsService;
use App\Services\DoctorCashRecordService;
use App\Services\DoctorListService;
use App\Services\DoctorWithdrawApplyService;
use App\Services\StoreCateService;
use App\Services\StoreGoodsService;
use App\Services\StoreOrderService;
use App\Services\StoreCartService;
use App\Services\StoreCommentService;
use App\Services\CouponListService;
class WxApp extends Controller{
	private $request;
	
	private $baseUserService;
	private $baseUserAddressService;
	private $baseBannerService;
	private $baseConfigService;
	private $articleCateService;
	private $articleNewsService;
	private $doctorCashRecordService;
	private $doctorListService;
	private $doctorWithdrawApplyService;
	private $storeCateService;
	private $storeGoodsService;
	private $storeOrderService;
	private $storeCartService;
	private $storeCommentService;
	private $couponListService;
	
    public function __construct(Request $request){
        $this->request = $request;
        $this->baseConfigService = new BaseConfigService();
        $this->baseUserService = new BaseUserService();
        $this->baseBannerService = new BaseBannerService();
        $this->baseUserAddressService = new BaseUserAddressService();
        $this->articleCateService = new ArticleCateService();
        $this->articleNewsService = new ArticleNewsService();
        $this->doctorCashRecordService = new doctorCashRecordService();
        $this->doctorListService = new DoctorListService();
        $this->doctorWithdrawApplyService = new DoctorWithdrawApplyService();
        $this->storeCateService = new StoreCateService();
        $this->storeGoodsService = new StoreGoodsService();
        $this->storeOrderService = new StoreOrderService();
        $this->storeCartService = new StoreCartService(); 
        $this->storeCommentService = new StoreCommentService();
        $this->couponListService = new CouponListService();   
    }
    
    //banner
    function getBannerList(){
    	$result = $this->baseBannerService->findAllInfo();
    	return response()->json($result);
    }
    
        
    /**
     * 获取配置信息
     */
    function getConfigInfo(){
    	$baseConfigService = new BaseConfigService();
		$result = $config = $baseConfigService->findAllKeyValue();
		return response()->json($result);
    }
    
    /**
     * 获取用户信息
     */
    function getUserInfo(){
    	$openId = $this->request->input('openId');
    	$result = $this->baseUserService->findInfo(array('openId'=>$openId));
    	return response()->json($result);
    }
    
    /**********************************产品模块****************************************/
   
    /**
     * 商品分类
     */
    function getGoodsCate(){
    	$result = $this->storeCateService->findAllInfo();
    	return response()->json($result);
    }
    
    /**
     * 分页加载商品
     */
    function paginateGoodsList(){
    	$cid = $this->request->input('cid');
    	$page = $this->request->input('page') ?? 1;
    	$pageSize = $this->request->input('pageSize') ?? 10;
    	$where[] = array('updown','=',1);
    	if(isset($cid) && $cid != '' && $cid !=0){
    		$where[] = ['cid','=',$cid];
    	}
    	
    	$result = $this->storeGoodsService->paginateGoods($where,$page,$pageSize);
    	return response()->json($result);
    }
    
    /**
     * 商品详情
     */
    function getGoodsDetail(){
    	$id = $this->request->input('id');
    	$result = $this->storeGoodsService->findInfo(array('id'=>$id));
    	return response()->json($result);
    }
    
    /**
     * 推荐商品
     */
    function recommendGoods(){
    	$where = array(['updown','=',1],['recommend','=',1]);
    	$result = $this->storeGoodsService->findAllInfo($where);
    	return response()->json($result);
    }
    
    /**
     * 搜索商品
     */
    function searchGoods(){
    	$title = $this->request->input('title');
    	$where = [['title','like','%'.$title.'%']];
    	$result = $this->storeGoodsService->findAllInfo($where);
    	return response()->json($result);
    }
    
    
    /*****************************订单模块************************************************/
    
    /**
     * 确认订单
     */
    function confirmOrder(){
    	$gids = $this->request->input('gids');
    	$counts = $this->request->input('counts');
    	$gidsArr  = explode(',',$gids);
    	$countsArr = explode(',',$counts);
    	$result = $this->storeGoodsService->findAllInfo(null,'id',$gidsArr);

    	$total_num = 0;
        $total_price = 0;
        for($i=0; $i < count($countsArr);$i++){
        	$result['data'][$i]->goods_count = $countsArr[$i];
        	$total_num += $countsArr[$i];
        	$total_price += $countsArr[$i] * $result['data'][$i]->price;
        }
        
        
        //地址
//      $userAddress = new BaseUserAddressService();
//      $addressResult = $userAddress->findInfo(array('user_id'=>$user_id,'is_default'=>1));
//      $address = $addressResult['data'];
        return response()->json(['code'=>1,'msg'=>'查询成功','data'=>['data'=>$result['data'],'total_num'=>$total_num,'total_price'=>$total_price]]);
       
    }
    
    
    /**
     * 0代付款 1已付款 2检测中 3报告已上传 4待评价 5已评价 6取消订单
     * 添加订单
     */
    function addOrder(){
		$userInfo['openId']       = $this->request->input('openId');;
		$userInfo['nickName']     = $this->request->input('nickName');
		$userInfo['avatarUrl']    = $this->request->input('avatarUrl');
		$message                  = $this->request->input('message');
		$gids                     = $this->request->input('gids');
		$counts                   = $this->request->input('counts');
		$cgids                    = $this->request->input('cgids');
		$coupon_code              = $this->request->input('coupon_code') ?? '';
		$result = $this->storeOrderService->addOrder($userInfo,$gids,$counts,$cgids,$message,$coupon_code);
    	return response()->json($result);
    }
     
     
     /**
      * 分页加载订单
      */
    function paginateOrder(){
    	$openId = $this->request->input('openId');
     	$status = $this->request->input('status');
    	$page = $this->request->input('page') ?? 1;
    	$pageSize = $this->request->input('pageSize') ?? 10;
    	$where[] = array('openId','=',$openId);
    	$where[] = array('is_user_delete','=',1);
    	if(isset($status) && $status != ''){
    		$where[] = array('status','=',$status);
    	}
    	$result = $this->storeOrderService->paginateOrder($where,$page,$pageSize);
    	return response()->json($result);
    }
    
    /**
     * 设置订单状态
     */
    function setStatus(){
    	$oid = $this->request->input('oid');
    	$status = $this->request->input('status');
    	$result = $this->storeOrderService->updateInfo(array('id'=>$oid),array('status'=>$status));
    	return response()->json($result);
    }
    
    /**
     * 用户删除订单
     */
    function userDeleteOrder(){
    	$oid = $this->request->input('oid');
    	$result = $this->storeOrderService->updateInfo(array('id'=>$oid),array('is_user_delete'=>0));
    	return response()->json($result);
    }
    
    /**
     * 查找优惠码
     */
    function getCouponCodeMOney(){
    	$coupon_code = $this->request->input('coupon_code');
    	$couponListResult = $this->couponListService->findInfo(array('coupon_code'=>$coupon_code));
		if($couponListResult['code'] != 1){
			return response()->json(['code'=>0,'msg'=>'优惠码不存在']);
		}else{
			$nowDate = date('Y-m-d');
			if($nowDate > $couponListResult['data']['end_time']){
				return response()->json(['code'=>0,'msg'=>'优惠码已过期']);

			}elseif($couponListResult['data']['is_use'] == 1){
				return response()->json(['code'=>0,'msg'=>'优惠码已使用']);
			}
		}
		
		return response()->json(['code'=>1,'msg'=>'优惠码金额','data'=>$couponListResult['data']['money']]);
    }
     
    /*****************************购物车模块**************************************/
    
    /**
     * 购物车列表
     */
    function getCartList(){
    	$user_id = $this->request->input('user_id');
    	$result = $this->storeCartService->leftJoinSql('store_cart','store_goods','store_cart.gid','=','store_goods.id');
    	return response()->json($result);
    }
    
    /*
     * 加入购物车
     */
    function insertCart(){
    	$gid     = $this->request->input('gid');
    	$count   = $this->request->input('count');
    	$user_id = $this->request->input('user_id');
    	
    	$where = array(
    		'gid'=>$gid,
    		'user_id'=>$user_id
    	);
    	$result = $this->storeCartService->findInfo($where);
    	if($result['code'] == 1){
    		$count = $count + $result['data']['count'];
    		$row = array('count'=>$count);
    		$result = $this->storeCartService->updateInfo($where,$row);
    	}else{
    		$row = array(
    			'gid'=>$gid,
    			'user_id'=>$user_id,
    			'count'=>$count
    		);
    		$result = $this->storeCartService->addInfo($row);
    	}
    	return response()->json($result);
    }
    
  /**
   * 更改购物车数量
   */
 	function updateCart(){
 		$id     = $this->request->input('id');
    	$count  = $this->request->input('count');
    	$row = array('count'=>$count);
    	$result = $this->storeCartService->updateInfo(array('id'=>$id),$row);
 		return response()->json($result);
 	}
    
    /**
     * 删除购物车
     */
    function deleteCart(){
    	$id = $this->request->input('id');
    	$result = $this->storeCartService->deleteInfo([['id','=',$id]]);
    	return response()->json($result);
    }
    
    /***********************************地址模块******************************************/
    /**
     * 新增用户地址
     */
    function insertAddress(){
    	$row = $this->request->all();
    	$result = $this->baseUserAddressService->addInfo($row);
    	return response()->json($result);
    }
    
    /**
     * 编辑用户地址
     */
    function updateAddress(){
    	$id = $this->request->input('id');
    	$row = $this->request->except('id');
    	$result = $this->baseUserAddressService->updateInfo(array('id'=>$id),$row);
    	return response()->json($result);
    }
    
    /**
     * 查询用户所有地址
     */
    function getAddressList(){
    	$user_id = $this->request->input('user_id');
    	$result = $this->baseUserAddressService->findAllInfo(array('user_id'=>$user_id));
    	return response()->json($result);
    }
    
    
    
    /**
     * 查询用户默认地址
     */
    function getDetaultAddress(){
    	$user_id = $this->request->input('user_id');
    	$result = $this->baseUserAddressService->findInfo(array('user_id'=>$user_id,'is_default'=>1));
    	return response()->json($result);
    }
    
    /**
     * 设置默认地址
     */
    function setDefaultAddress(){
    	$user_id = $this->request->input('user_id');
    	$id = $this->request->input('id');
    	$result = $this->baseUserAddressService->updateInfo(array('user_id'=>$user_id),array('is_default'=>0));
    	if($result['code'] == 1){
    		$result = $this->baseUserAddressService->updateInfo(array('id'=>$id),array('is_default'=>1));
    	}
    	return response()->json($result);
    }
    
    /**************************************评论模块****************************************/
    function addComment(){
    	$row = $this->request->except('oid');
    	$result = $this->storeCommentService->addInfo($row);
    	if($result['code'] == 1){
    		$oid= $this->request->input('oid');
    		$orderResult = $this->storeOrderService->findInfo(array('id'=>$oid));
    		$goodsList = json_decode($orderResult['data']['goods_list'],true);
    		foreach($goodsList as $value){
    			$goodsResult = $this->storeGoodsService->findInfo(array('id'=>$value['gid']));
    			if($goodsResult['data']['commentIds']){
    				$commentIds = $goodsResult['data']['commentIds'] . ','.$result['data'];
    			}else{
    				$commentIds = $result['data'];
    			}
    			
    			$this->storeGoodsService->updateInfo(array('id'=>$value['gid']),array('commentIds'=>$commentIds));
    		}
    	}
    	return response()->json($result);	
    }
    
    /**
     * 获取评论
     */
    function getCommentList(){
    	$gid = $this->request->input('id');
    	$goodsResult = $this->storeGoodsService->findInfo(array('id'=>$gid));
    	$commentArr = explode(',',$goodsResult['data']['commentIds']);
    	$result = $this->storeCommentService->findAllInfo(null,'id',$commentArr);
    	
    	return response()->json($result);	
    }
    
    /***********************************资讯模块************************************/
    
    
    //资讯分类
    function getArticleCate(){
    	$result = $this->articleCateService->findAllInfo();
    	return response()->json($result);
    }
    
    //资讯列表
    function paginateArticleList(){
    	$cid = $this->request->input('cid');
    	$page = $this->request->input('page') ?? 1;
    	$pageSize = $this->request->input('pageSize') ?? 10;
    	$where = array();
    	if(isset($cid) && $cid != ''){
    		$where = array('cid'=>$cid);
    	}
    	$result = $this->articleNewsService->paginateNews($where,$page,$pageSize);
    	return response()->json($result);
    }
    
    /**
     * 资讯详情
     */
    function getArticleDetail(){
    	$id = $this->request->input('id');
    	$sql = "update xk_article_news set view_num = view_num + 1 where id = {$id}";
		$this->articleNewsService->updateSql($sql);
    	$result = $this->articleNewsService->findInfo(array('id'=>$id));
    	return response()->json($result);
    }
    
    /**
     * 随机获得新闻
     */
    function getArticleList(){
    	$limit = $this->request->input('limit');
    	$result = $this->articleNewsService->findAllInfo(null,$limit);
    	return response()->json($result);
    }
    
    /****************************************医生模块************************/
    function addApplyDoctor(){
    	$param = $this->request->input();
    	$doctorResult = $this->doctorListService->findInfo(array('user_id'=>$param['user_id']));
    	if($doctorResult['code'] == 1){
    		return response()->json(['code'=>0,'msg'=>'不可重复申请']);exit;
    	}
    	$result = $this->doctorListService->addInfo($param);
    	return response()->json($result);
    }
    
    /***
     * 医生信息
     */
    function getDoctorInfo(){
    	$user_id = $this->request->input('user_id');
    	$result = $this->doctorListService->findInfo(array('user_id'=>$user_id));
    	return response()->json($result);
    }
    
    /**
     * 粉丝列表
     */
    function paginateMyFans(){
    	$user_id = $this->request->input('user_id');
    	$page = $this->request->input('page') ?? 1;
    	$pageSize = $this->request->input('pageSize') ?? 10;
    	$where = array('parent_user_id'=>$user_id);
    	$result = $this->baseUserService->paginateUser($where,$page,$pageSize);
    	return response()->json($result);
    }
    
     /**
     * 佣金列表
     */
    function paginateCashRecord(){
    	$doctor_id = $this->request->input('doctor_id');
    	$page = $this->request->input('page') ?? 1;
    	$pageSize = $this->request->input('pageSize') ?? 10;
    	$where = array('doctor_id'=>$doctor_id);
    	$result = $this->doctorCashRecordService->paginateCashRecord($where,$page,$pageSize);
    	return response()->json($result);
    }
    
    /**
     * 申请提现
     */
    function withdrawApply(){
    	$doctor_id = $this->request->input('doctor_id');
    	$money = $this->request->input('money');
    	$doctorResult = $this->doctorListService->findInfo(array('id'=>$doctor_id));
    	if($doctorResult['code'] !=1)return response()->json(['code'=>0,'用户不存在','']);
    	else{
    		
    		$left_fee   = floatval($doctorResult['data']['left_fee']);
    		$money      = floatval($money);
    		if($left_fee < $money ) return response()->json(['code'=>0,'余额不足','']);
    		else{
    			$applyRow = array(
    				'doctor_id'=>$doctor_id,
    				'money'=>$money,
    				'name'=>$doctorResult['data']['name'],
    				'created_at'=>date('Y-m-d H:i:s'),
    				'updated_at'=>date('Y-m-d H:i:s'),
    			);
    			$result = $this->doctorWithdrawApplyService ->withdrawApply($doctor_id,$applyRow,$money);
    			return response()->json($result);
    		}
    	}
    }
    
    /**
     * 获取小程序码
     */
    function getWxCode(){
    	$user_id = $this->request->input('user_id');
    	$result = $this->doctorListService->findInfo(array('user_id'=>$user_id));
    	if($result['code'] == 1 && $result['data']['code'] != ''){
    		$code = $result['data']['code'];
    	}else{
    		$code = $this->createWxCode($user_id);
    		$this->doctorListService->updateInfo(array('user_id'=>$user_id),array('code'=>$code));
    	}
    	return response()->json(['code'=>1,'msg'=>'成功','data'=>$code]);
    }
    
    /**
     * 生成小程序码
     */
    function createWxCode($parent_user_id){
 		
    	require_once '../app/libs/utils/Curl.php';
    	$access_token = $this->getAccessToken();
    	$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
    	$scene = $parent_user_id;
		$width='280';
		$colorArr = array('r'=>'55', 'g'=>'180', 'b'=>'54');
		$line_color	 = json_encode($colorArr);
		$post_data='{"page":"'.$page.'","scene":"'.$scene.'","width":"'.$width.'","line_color":"'.$line_color.'"}';
    	$result = \Curl::callWebServer($url,$post_data,'post');
    	
    	$res = '';
    	if(empty($result['errcode'])){
    		$time = time();
			$str = rand(100, 999);
			$name = $time.'_'.$str.'.png';
			$filepath = 'storage/wxCode/'.$name;
			file_put_contents($filepath, $result);
			$res = $filepath;
    	}
    	return $res;	
    }
    
   
    /**
    * 获取ACCESS_TOKEN
   */

	function getAccessToken()
    {
    	require_once '../app/libs/utils/Curl.php';
    	if(!file_exist('access_token.txt')){
    		file_put_contents('access_token.txt','');
    	}
		$jsonArr = file_get_contents('access_token.txt');
		$jsonArr = json_decode($jsonArr,true);
		$now_time = time();
		$left = $now_time - $jsonArr['save_time'];
		
		if($left < 3000){
			return $jsonArr['access_token'];
		}else{
			$appid     = config('baseConfig.mini_appid');
            $appsecret = config('baseConfig.mini_appsecret');
			
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
			$result = \Curl::callWebServer($url);
			if($result['access_token']){
				$jsonArr = array('access_token'=>$result['access_token'],'save_time'=>time());
				file_put_contents('access_token.txt',json_encode($jsonArr));
				return $result['access_token'];
			}else{
				return '';
			}
		}
		
	}
    
    
    /**
     * 上传图片
     */
    function upload(){
    	$file = $this->request->file('file');
        $uploadDir = "front" . '/' .date('Y-m-d');
        $path = $file->store($uploadDir, 'public');
		$path = '/storage/'.$path;
    	return response()->json(['code'=>1,'msg'=>'上传成功','data'=>$path]);
    }
    
    
    /**
     * 微信支付 统一下单
     */
    function wxPay(){
    	
    	require_once '../app/libs/utils/pay_sdk/lib/WxPay.Api.php';
    	require_once '../app/libs/utils/pay_sdk/example/WxPay.JsApiPay.php';
    	require_once '../app/libs/utils/pay_sdk/example/WxPay.Config.php';
		$oid = $this->request->input('oid');
		$orderResult = $this->storeOrderService->findInfo(array('id'=>$oid));
		$orderInfo = $orderResult['data'];
		
		$configResult = $this->baseConfigService->findAllKeyValue();
	
		$wechat_pay_title = $configResult['data']['wechat_pay_title'];
		$wechat_notify_url= $configResult['data']['wechat_notify_url'];
		try{
			//②、统一下单
			$input = new \WxPayUnifiedOrder();
			$input->SetBody($wechat_pay_title);
			$input->SetOut_trade_no($orderInfo['order_num']);
			$input->SetTotal_fee($orderInfo['total_price'] * 100);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			$input->SetNotify_url($wechat_notify_url);
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid($orderInfo['openId']);
			$config = new \WxPayConfig();
			$order = \WxPayApi::unifiedOrder($config, $input);
			
			$tools = new \JsApiPay();
			$jsApiParameters = $tools->GetJsApiParameters($order);
			$jsApiParameters = json_decode($jsApiParameters,true);
			return response()->json(['code'=>1,'msg'=>'成功','data'=>$jsApiParameters]);
			
		} catch(Exception $e) {
			
		}
    }
    
    /**
     * 支付成功
     */
    function notifyUrl(){
    	
    	require_once '../app/libs/utils/pay_sdk/lib/WxPay.BankCard.php';
    	$postStr = file_get_contents('php://input');
		libxml_disable_entity_loader(true);
		$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
		file_put_contents('a.txt',$postObj);
		if( $postObj->return_code == "SUCCESS"){
			if($postObj->result_code == "SUCCESS"){ 			
				$orderInfoData = array(
					'status' => 1,//设置待发货
					'transaction_id' => $postObj->transaction_id,
					'pay_card' =>\BankCard::GetBankCard($postObj->bank_type),
				);
				
				$order_num = $postObj->out_trade_no;
				$orderResult = $this->storeOrderService->findInfo(array('order_num'=>$order_num));
				if($orderResult['data']['transaction_id']){
					return 'success';
					exit;
				}else{
					
					$result = $this->storeOrderService->updateInfo(array('order_num'=>$order_num),$orderInfoData);
					if($result['code'] == 1){
						$goodsList = json_decode($orderResult['data']['goods_list'],true);
						foreach ($goodsList as $goods){
							$this->storeGoodsService->decreSql('store_goods','inventory',$goods['goods_count']);
						}
					}
				}
			}
		}
				
    }
    
    
    
    /**
     * 短信发送
     */
    function sendSms(){
    	require_once '../app/libs/utils/Curl.php';
    	$url = "http://112.124.24.5/api/MsgSend.asmx/SendMsg";
    	$arr = array(
    		'userCode'=>'安房网',
    		'userPass'=>'anfangwang',
    		'DesNo'=>'18375325618',
    		'Msg'=>'完成支付测试【安房网】',
    		'Channel'=>'37',
    	);
    	$result = \Curl::callWebServer($url,$arr);
    	var_dump($result);
    }
    
    /**
     * 发送短信 工具方法
     */
    function sendSmsTool($userPhone,$msg='支付完成【安房网】'){
    	require_once '../app/libs/utils/Curl.php';
    	$url = "http://112.124.24.5/api/MsgSend.asmx/SendMsg";
    	$arr = array(
    		'userCode'=>'安房网',
    		'userPass'=>'anfangwang',
    		'DesNo'=>$userPhone,
    		'Msg'=>$msg,
    		'Channel'=>'37',
    	);
    	\Curl::callWebServer($url,$arr);
    }
    
    
    /****************                  小程序登录                                    **************************/
    /**
     * auth.code2Session 登录凭证校验
     */
    function authCode2Session(){
    	require_once '../app/libs/utils/Curl.php';
        $js_code = $this->request->input('code');
        $appid = config('baseConfig.mini_appid');
        $secret = config('baseConfig.mini_appsecret');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$js_code}&grant_type=authorization_code";
        $result = \Curl::callWebServer($url);

        if(isset($result['openid'])){
            $openId      = $result['openid'];
            $session_key = $result['session_key'];
            Cache::put($openId,$session_key,3600);
            return response()->json(['code'=>1,'msg'=>'请求成功','openId'=>$openId]);
        }else{
        	return response()->json(['code'=>0,'msg'=>'请求失败','']);
        }
    }

    /**
     *获取用户信息
     */
    function getLoginUserInfo(){
        $rawData = $this->request->input('rawData');
        $signature = $this->request->input('signature');
        $openId = $this->request->input('openId');
        $encryptedData = $this->request->input('encryptedData');
        $iv = $this->request->input('iv');
        $parent_user_id = $this->request->input('did');
     
        $session_key = Cache::get($openId);
        $signature2 = sha1( $rawData.$session_key);

        if($signature == $signature2){//数据安全
            require_once '../app/libs/utils/miniprogram/userUtil/wxBizDataCrypt.php';

            $appid = config('baseConfig.mini_appid');
            $sessionKey = $session_key;
            $encryptedData = $encryptedData;
            $iv = $iv;

            $pc = new \WXBizDataCrypt($appid, $sessionKey);
            $errCode = $pc->decryptData($encryptedData, $iv, $data );

            if ($errCode == 0) {//获取用户信息成功
               	$data = json_decode($data,true);//用户信息
              
                $result = $this->baseUserService->findInfo(array('openId'=>$openId));
                if($result['code'] == 1){//数据库已存在
                    $data = $result['data'];
                }else{//插入数据库
                    $row = array(
                        'openId'=>$data['openId'],
                        'nickName'=>$data['nickName'],
                        'avatarUrl'=>$data['avatarUrl'],
                        'gender'=>$data['gender'],
                        'country'=>$data['country'],
                        'province'=>$data['province'],
                        'city'=>$data['city'],
                        'parent_user_id'=>$parent_user_id
                    );
                   
                    $this->baseUserService->addInfo($row);
                }
                return response()->json(['code'=>1,'msg'=>'请求成功','data'=>$data]);
            } else {
                $data = $errCode;
                return response()->json(['code'=>0,'msg'=>'请求失败',$data]);  
            }

        }else{//数据不安全
            return response()->json(['code'=>0,'msg'=>'请求失败','']);  
        } 
    }
    
  }  
?>